/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package io.iec.edp.caf.tenancy.core.service;

import io.iec.edp.caf.tenancy.api.ITenantRouteEx;
import io.iec.edp.caf.tenancy.api.ITenantRouteService;
import io.iec.edp.caf.tenancy.api.exception.TenantNotFoundException;
import io.iec.edp.caf.tenancy.api.service.TenantRoutingService;
import io.iec.edp.caf.tenancy.core.utils.DataValidator;
import lombok.NonNull;

import java.util.HashMap;
import java.util.List;

/**
 * 租户路由服务实现
 *
 * @author guowenchang
 * @date 2021-01-15
 */
public class TenantRouteServiceImpl implements ITenantRouteService {
    private final HashMap<String, ITenantRouteEx> routerMap = new HashMap<>();
    private final TenantRoutingService tenantRoutingManager;

    public TenantRouteServiceImpl(List<ITenantRouteEx> customRouters, TenantRoutingService tenantRoutingManager) {
        this.tenantRoutingManager = tenantRoutingManager;
        for (ITenantRouteEx router : customRouters) {
            String suName = router.getSuName();
            DataValidator.checkForEmptyString(suName, "suName");
            routerMap.put(router.getSuName().toLowerCase(), router);
        }
    }

    @Override
    @NonNull
    public Integer route(String suName, String tenantDim1, String tenantDim2) throws TenantNotFoundException {
        DataValidator.checkForEmptyString(suName, "suName");
        //先看有没有自定义实现 有就走他们的
        if (routerMap.containsKey(suName.toLowerCase())) {
            return routerMap.get(suName.toLowerCase()).route(tenantDim1, tenantDim2);
        }

        return doRoute(suName, tenantDim1, tenantDim2);
    }

    @NonNull
    private Integer doRoute(String suName, String tenantDim1, String tenantDim2) throws TenantNotFoundException {
        Integer result = tenantRoutingManager.getTenantId(suName, tenantDim1, tenantDim2);

        if (result == null) {
            throw new TenantNotFoundException(suName, tenantDim1, tenantDim2);
        }

        return result;
    }
}
